import { getOssSignatureApi } from '@/api/message'
import { createUUID } from '@/utils/createUUID'

/**
 * 上传文件至OSS
 */
export function uploadFile2OSS({ tempFilePath, fileType = 'image' }) {
  return new Promise(async (resolve, reject) => {
    // 获取文件扩展名
    const fileExt = tempFilePath.slice(tempFilePath.lastIndexOf('.') + 1)
    // 获取直传签名
    const signatureRes = await getOssSignatureApi()
    // 解构
    const { host, pathPrefix, policy, signature, ossAccessKeyId } = signatureRes
    // 构造 formData
    const formData = {
      key: `${pathPrefix}/${createUUID()}.${fileExt}`,
      policy,
      OSSAccessKeyId: ossAccessKeyId,
      signature,
      success_action_status: 200
    }
    // 上传文件至OSS
    uni.uploadFile({
      url: host,
      fileType,
      filePath: tempFilePath,
      name: 'file',
      formData,
      success: (res) => {
        if (200 === res.statusCode) {
          // 文件路径
          const filePath = host + formData.key

          resolve(filePath)
        }
      },
      fail: (error) => {
        reject(error)
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  })
}
